package cn.starlightsoftware.sherly.convertor;


import org.mapstruct.Mapper;
import org.mapstruct.Mapping;
import org.mapstruct.factory.Mappers;
import cn.starlightsoftware.sherly.controller.admin.permission.vo.PermissionRespVO;
import cn.starlightsoftware.sherly.controller.admin.permission.vo.PermissionSimpleRespVO;
import cn.starlightsoftware.sherly.db.model.permission.PermissionDO;

import java.util.Comparator;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * @author 谷子毅
 * @date 2024/4/28
 */
@Mapper
public interface PermissionConvertor {

    PermissionConvertor PermissionConvertor = Mappers.getMapper(PermissionConvertor.class);

    @Mapping(target = "children", ignore = true)
    PermissionRespVO toRespVO(PermissionDO permission);

    @Mapping(target = "children", ignore = true)
    PermissionSimpleRespVO toSimpleRespVO(PermissionDO permission);

    static List<PermissionRespVO> buildTree(List<PermissionDO> list) {
        // 对象转换成VO类型
        List<PermissionRespVO> all = list.stream().map(PermissionConvertor::toRespVO)
                .sorted(Comparator.comparing(PermissionRespVO::getSort)).collect(Collectors.toList());

        return all.stream().filter(e -> Objects.equals(e.getParentId(), "0"))
                .peek(e -> e.setChildren(getChildren(e, all)))
                .collect(Collectors.toList());
    }

    static List<PermissionRespVO> getChildren(PermissionRespVO parent, List<PermissionRespVO> all) {
        return all.stream()
                .filter(e -> Objects.equals(e.getParentId(), parent.getPermissionId()))
                .peek(e -> e.setChildren(getChildren(e, all)))
                .collect(Collectors.toList());
    }

    static List<PermissionSimpleRespVO> buildSimpleTree(List<PermissionDO> list) {
        // 对象转换成VO类型
        List<PermissionSimpleRespVO> all = list.stream().map(PermissionConvertor::toSimpleRespVO)
                .sorted(Comparator.comparing(PermissionSimpleRespVO::getSort)).collect(Collectors.toList());

        return all.stream().filter(e -> Objects.equals(e.getParentId(), "0"))
                .peek(e -> e.setChildren(getSimpleChildren(e, all)))
                .collect(Collectors.toList());
    }

    static List<PermissionSimpleRespVO> getSimpleChildren(PermissionSimpleRespVO parent, List<PermissionSimpleRespVO> all) {
        return all.stream()
                .filter(e -> Objects.equals(e.getParentId(), parent.getPermissionId()))
                .peek(e -> e.setChildren(getSimpleChildren(e, all)))
                .collect(Collectors.toList());
    }
}
